/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.infinityk.simplesoundengine.test;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.swing.DropMode;
import javax.swing.JList;
import javax.swing.TransferHandler;
import javax.swing.TransferHandler.TransferSupport;

/**
 *
 * @author Asier
 */
class ListFileDrop extends TransferHandler{
    private GenericListModel<SoundFileEntry> model;
    
    public static void addDroper(JList field,GenericListModel<SoundFileEntry> model){
        field.setDragEnabled(true);
        field.setDropMode(DropMode.INSERT);
        field.setTransferHandler( new ListFileDrop(model) );
    }
    
    public ListFileDrop(GenericListModel<SoundFileEntry> model) {
        this.model = model;
    }

    
    @Override
    public boolean canImport(TransferSupport support) {
        if (support.isDataFlavorSupported(DataFlavor.javaFileListFlavor)){
            support.setDropAction(COPY);
            return true;
        }
        return false;
    }

    @Override
    public boolean importData(TransferSupport support) {
       if (support.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            try{
                List<File> files = (List<File>) support.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
                if(! files.isEmpty()){
                    if (support.getComponent() instanceof JList){
                        JList list = (JList)support.getComponent();
                        for(File f : files){
                            String name = f.getName().toLowerCase();
                            if (name.endsWith(".wav") || name.endsWith(".ogg")){
                                model.add(new SoundFileEntry(f));
                            }
                        }
                    }
                }
                return true;
            }catch(UnsupportedFlavorException e ){ e.printStackTrace();
            }catch(IOException e) {e.printStackTrace();}
        }
        return false;
    }
    
}